const arr = [1, 2, 3, 4]
//求和
const total = arr.reduce((prev, curr) => prev + curr)
const arr1 = [
  {
    id: 1,
    age: 18,
    name: 'hikaru'
  },
  {
    id: 2,
    age: 18,
    name: 'shindou'
  },
  {
    id: 3,
    age: 22,
    name: 'peter'
  },
  {
    id: 4,
    age: 32,
    name: 'tom'
  }
]
//求所有age的和
const ageTotal = arr1.reduce((prev, curr) => { return prev + curr.age }, 0)
//按id分类
const idObj = arr1.reduce((prev, curr) => {
  prev[curr.id] = curr
  return prev
}, {})
//按age分类
const ageArr = arr1.reduce((prev, curr) => {
  let index = prev.findIndex(item => item.age === curr.age)
  if (index >= 0) {
    prev[index].list.push(curr)
  } else {
    prev.push({
      age: curr.age,
      list: [curr]
    })
  }
  return prev

}, [])
const arr2 = [
  { id: 1, name: 'a' },
  { id: 12, name: 'aa', parentId: 1 },
  { id: 121, name: 'a', parentId: 12 },
  { id: 122, name: 'a', parentId: 12 },
  { id: 2, name: 'b' },
  { id: 22, name: 'ba', parentId: 2 },
  { id: 221, name: 'baa', parentId: 22 },
  { id: 222, name: 'bab', parentId: 22 },
]
const result = arr2.reduce((prev, curr, i, arr) => {
  curr.children = arr.filter(v => v.parentId === curr.id)
  if (!curr.parentId) {
    prev.push(curr)
  }
  return prev

}, [])
console.log({
  total,
  ageTotal,
  idObj,
  ageArr: JSON.stringify(ageArr, null, 2),
  result: JSON.stringify(result, null, 2)
})
